$.getUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
$(function() {
    var imageIds = '';
    var objTypes = '';
    var tempLength = 0; //临时变量,当前移动的长度

    var chooseDefaul;
    var chooseList;

    var wsInfo = {
        isRepeatArr: function(arr, item) {
            for(var i = 0, len = arr.length;i < len;i++) {
                if(arr[i] == item) {
                    return true;
                }
            }
            return false;
        },
        getDetailGoods: function() {
            $.ajax({
                url: wsCommon.host + '/api/goods/queryDetailGoods/'+$.getUrlParam('goodsId'),
                dataType: wsCommon.jsonType,
                success: function(res) {
                    var product = res.data.product;
                    var salesRuleGoodsList = res.data.salesRuleGoodsList;
                    var imageList = res.data.imageList;
                    var typePropsList = res.data.typePropsList;
                    var salesRuleOrderList = res.data.salesRuleOrderList;
                    var specificationList = res.data.specificationList;
                    var relateProducts = res.data.relateProducts;
                    var storeRelateProducts = res.data.storeRelateProducts;
                    chooseList = imageList;
                    chooseDefaul = product.defaultImage;

                    var viewHistory = wsCommon.getCookie('view_history');
                    if(viewHistory == null) {
                        viewHistory = product.productId;
                        wsCommon.setCookie('view_history', viewHistory);
                    } else {
                        var viewHistoryArr = viewHistory.split(',');
                        if(!wsInfo.isRepeatArr(viewHistoryArr, product.productId)) viewHistory = product.productId+','+viewHistory;
                        wsCommon.setCookie('view_history', viewHistory.split(',').slice(0,12).join(','));
                    }

                    $('[data-product="name"]').html(product.name);
                    $('[data-product="brief"]').html(product.brief);
                    $('[data-product="price"]').html('¥' + product.price);
                    // $('[data-product="mktprice"]').html('¥' + product.mktprice);
                    $('[data-product="bn"]').html(product.bn);
                    $('[data-product="brand"]').html(product.brand).attr('href', './brandList.html?brandId='+product.brandId);
                    $('[data-product="barCode"]').html(product.barcode);
                    $('[data-product="score"]').html(product.score);
                    $('[data-product="murl"] img').attr('src', product.defaultImage.murl).attr('jqimg', product.defaultImage.lurl);

                    imageIds = product.defaultImage.imageId;
                    objTypes = product.objType;
                    if(product.store > 0) {
                        $('[data-product="store"]').prepend('<input type="button" style="cursor:pointer; border:0; width:142px; height:42px; background: url(images/btn-joincart.jpg) no-repeat 0 0" class="btn-major btn-huge action-addtocart btn-joincart" id="add_c" value="" data-role="addShopCart" data-style="info" data-price="'+product.price+'" data-goodsid="'+product.goodsId+'" data-productid="'+product.productId+'" data-objtype="'+product.objType+'">');
                    } else {
                        $('[data-product="store"]').append('<button type="button" class="btn btn-caution btn-huge action-notify" id="notice" data-goodsid="'+product.goodsId+'" data-productid="'+product.productId+'" data-name="'+product.name+'" data-price="'+product.price+'" data-img="'+product.defaultImage.imageId+'"><span><span>到货通知</span></span></button>');
                        $('.product-buy-quantity').hide();
                    }
                    if(product.fav) {
                        $('[data-product="store"]').append('<a href="javascript:;" class="btn btn-faved" style="margin-left: 10px;"><em>已收藏</em></a>');
                    } else {
                        $('[data-product="store"]').append('<a href="javascript:;" class="btn btn-addfav" data-role="addInfofav" style="margin-left: 10px;" data-goodsid="'+product.goodsId+'" data-productid="'+product.productId+'" data-name="'+product.name+'" data-price="'+product.price+'" data-img="'+product.defaultImage.imageId+'"> <i class="icon"> F </i>收藏</a>');
                    }
                    $('.btn-increase, .action-quantity-input').attr('data-total', product.store);
                    $('.btn-decrease, .action-quantity-input').attr('data-total', product.store);
                    //  送货时间
                    if(res.data.shipInfo != null) {
                        $('[data-role="shipInfo"]').html('由<strong>' + res.data.shipInfo.shipName + '</strong>发货,'+ res.data.shipInfo.shipTime);
                    }


                    //限购
                    if(product.isTriction == 1) {
                        $('[data-role="xiangou"]').find('span').html(product.trictQuantity).end().show()
                    }


                    // salesRuleGoodsList
                    // salesRuleGoodsList = null;
                    if(salesRuleGoodsList != null && typeof(salesRuleGoodsList) != 'undefined') {
                        var salesRuleGoodsListTpl = '';
                         salesRuleGoodsListTpl += '<div class="switchable-panel">\
                             <div class="panel-top">\
                                 <ul>';
                        $.each(salesRuleGoodsList, function(index, item) {
                            salesRuleGoodsListTpl += '<li><span class="name" style="color:#5EB107">'+item.name+'</span></li>';
                        })
                        salesRuleGoodsListTpl += '</ul></div></div>';
                        $('[data-role="salesListWrap"]').append(salesRuleGoodsListTpl);
                        $('[data-role="salesList"]').append('<li class="active"><em>商品促销</em></li>');
                    }

                    // salesRuleOrderList
                    // salesRuleOrderList = null;
                    if(salesRuleOrderList != null && typeof(salesRuleOrderList) != 'undefined') {
                        var salesRuleOrderListTpl = '';
                        if(salesRuleGoodsList != null && typeof(salesRuleGoodsList) != 'undefined') {
                            $('[data-role="salesList"]').append('<li class=""><em>订单促销</em></li>');
                            salesRuleOrderListTpl += '<div class="switchable-panel" style="display: none;">\
                                <div class="panel-top">\
                                    <ul>';
                        } else {
                            $('[data-role="salesList"]').append('<li class="active"><em>订单促销</em></li>');
                            salesRuleOrderListTpl += '<div class="switchable-panel">\
                                <div class="panel-top">\
                                    <ul>';
                        }

                        $.each(salesRuleOrderList, function(index, item) {
                            salesRuleOrderListTpl += '<li><span class="name" style="color:#5EB107">'+item.name+'</span></li>';
                        })
                        salesRuleOrderListTpl += '</ul></div></div>';
                        $('[data-role="salesListWrap"]').append(salesRuleOrderListTpl);
                    }

                    // intro
                    $('[data-role="intro"]').html(product.intro);

                    var imageListTpl = '';
                    $.each(imageList, function(index, item) {
                        if(imageIds == item.imageId) {
                            imageListTpl += '<li><img alt="'+item.imageName+'" bimg="'+item.lurl+'" src="'+item.murl+'" onmousemove="preview(this);" style="background-color: rgb(94, 177, 7);"></li>';
                        } else {
                            imageListTpl += '<li><img alt="'+item.imageName+'" bimg="'+item.lurl+'" src="'+item.murl+'" onmousemove="preview(this);"></li>';
                        }

                    })
                    $('[data-imageList="list"] ul').html(imageListTpl);
                    //图片预览小图移动效果
                	var viewNum = 5; //设置每次显示图片的个数量
                	var moveNum = 2; //每次移动的数量
                	var moveTime = 300; //移动速度,毫秒
                	var scrollDiv = $(".spec-scroll .items ul"); //进行移动动画的容器
                	var scrollItems = $(".spec-scroll .items ul li"); //移动容器里的集合
                	var moveLength = scrollItems.eq(0).outerWidth() + 8; //计算每次移动的长度
                	var countLength = (scrollItems.length - viewNum) * scrollItems.eq(0).width(); //计算总长度,总个数*单个长度

                	//下一张
                	$(document).on("click",".spec-scroll .next", function(){
                		if(tempLength < countLength){
                			if((countLength - tempLength) > moveLength){
                				scrollDiv.animate({left:"-=" + moveLength + "px"}, moveTime);
                				tempLength += moveLength;
                			}else{
                				scrollDiv.animate({left:"-=" + (countLength - tempLength) + "px"}, moveTime);
                				tempLength += (countLength - tempLength);
                			}
                		}
                	});
                	//上一张
                	$(document).on("click",".spec-scroll .prev",function(){
                		if(tempLength > 0){
                			if(tempLength > moveLength){
                				scrollDiv.animate({left: "+=" + moveLength + "px"}, moveTime);
                				tempLength -= moveLength;
                			}else{
                				scrollDiv.animate({left: "+=" + tempLength + "px"}, moveTime);
                				tempLength = 0;
                			}
                		}
                	});

                    var specificationListTpl = '';
                    $.each(specificationList, function(index, item) {
                        specificationListTpl += '<li class="item clearfix">\
                                                    <span class="label"> 选择'+item.specName+'：</span>\
                                                    <span class="detail">';
                        $.each(item.specValuesList, function(indexDir, itemDir) {
                            var classData = '';
                            // if(indexDir == 0) {
                            //     classData = 'item-selected';
                            // }
                            var imgTpl = '';
                            if(itemDir.specImage) {
                                imgTpl = '<img src="'+itemDir.specImage+'" width="25" height="25" />';
                            }
                            specificationListTpl += '<div class="consignee-item '+classData+'" data-id="'+itemDir.specValueId+'">\
                                                        <span title="'+itemDir.specValue+'">'+ imgTpl + itemDir.specValue+'</span><b></b>\
                                                    </div>';
                        })
                        specificationListTpl += '</span></li>';
                    })
                    $('[data-specificationList="list"]').append(specificationListTpl);

                    var storeRelateProductsTpl = '';
                    $.each(storeRelateProducts, function(index, item) {
                        storeRelateProductsTpl += '<li class="item clearfix">\
                                                    <span class="label">选择产品：</span>\
                                                    <span class="detail">';
                        var imgTpl = '';
                        if(item.defaultImage) {
                            if(typeof(item.defaultImage.surl) != 'undefined') {
                                imgTpl = '<img src="'+item.defaultImage.surl+'" width="25" height="25" />';
                            }
                        }
                        storeRelateProductsTpl += '<div class="consignee-item">\
                                                        <a href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'" style="color:#666;text-decoration:none;">'+ imgTpl+ item.name+'</a>\
                                                    </div>';

                        storeRelateProductsTpl += '</span></li>';
                    })
                    $('[data-specificationList="list"]').append(storeRelateProductsTpl);

                    var relateProductsTpl = '';
                    $.each(relateProducts, function(index, item) {
                        relateProductsTpl += '<li class="item clearfix">\
                                                    <span class="label">相关产品：</span>\
                                                    <span class="detail">';
                        var imgTpl = '';
                        if(item.defaultImage) {
                            if(typeof(item.defaultImage.surl) != 'undefined') {
                                imgTpl = '<img src="'+item.defaultImage.surl+'" width="25" height="25" />';
                            }
                        }
                        relateProductsTpl += '<div class="consignee-item">\
                                                        <a href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'" style="color:#666;text-decoration:none;">'+ imgTpl+ item.name+'</a>\
                                                    </div>';

                        relateProductsTpl += '</span></li>';
                    })
                    $('[data-specificationList="list"]').append(relateProductsTpl);

                    // 规格选中
                    $.each(product.specValueList, function(index, item) {
                        $('[data-id="'+item+'"]').addClass('item-selected');
                    })
                },
                error: function() {
                    // console.log('queryDetailGoods返回失败');
                }
            })
        },
        // 收藏
        addFav: function() {
            $(document).on('click', '[data-role="addInfofav"]', function() {
                var $this = $(this);
                $.ajax({
                    url: wsCommon.host + '/api/memberGoods/fav',
                    dataType: wsCommon.jsonType,
                    data: {
                        goodsId: $this.attr('data-goodsid'),
                        productId: $this.attr('data-productid'),
                        goodsName: $this.attr('data-name'),
                        goodsPrice: $this.attr('data-price'),
                        imageDefaultId: $this.attr('data-img')
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(res.result) {
                                $this.removeClass('btn-addfav').addClass('btn-faved').html('<em>已收藏</em>');
                            } else {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                            }

                        }
                    },
                    error: function() {
                        // console.log('收藏接口返回失败');
                    }
                })
            })
        },

        // 到货通知
        arrivalNotice: function() {
            //弹层
    		$(document).on('click',"#notice" ,function(){
    		   $(".cover").show();
    		   $("#notice_pop").show();

    		})
    		$(document).on('click', ".popup-btn-close", function(){
    		   $(this).parents(".popup-container").hide();
    		   $(".cover").hide();
    		})

            // 提交
            $(document).on('click', '[data-role="arrivalNotice"]', function() {
                var email = $('[data-arrivalNotice="email"]').val().trim();
                var phone = $('[data-arrivalNotice="phone"]').val().trim();
                var phonereg = /^((13[0-9])|(15[^4,\D])|(18[0,3-9]))\d{8}$/;
                var emailreg = /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/;
                if(email == '' && phone == '') {
                    iosOverlay({
                        text: "邮箱地址和手机号码至少填写一个!",
                        duration: 1500
                    });
                    return;
                } else if(!emailreg.test(email) && email != '') {
                    iosOverlay({
                		text: "邮箱格式不正确!",
                        duration: 1500
                	});
                    return;
                } else if(!phonereg.test(phone) && phone != '') {
                    iosOverlay({
                		text: "手机号码格式不正确!",
                        duration: 1500
                	});
                    return;
                } else {
                    var noticeDom = $('#notice');
                    $.ajax({
                        url: wsCommon.host + '/api/memberGoods/save',
                        dataType: wsCommon.jsonType,
                        data: {
                            goodsId: noticeDom.attr('data-goodsid'),
                            productId: noticeDom.attr('data-productid'),
                            goodsName: noticeDom.attr('data-name'),
                            goodsPrice: noticeDom.attr('data-price'),
                            imageDefaultId: noticeDom.attr('data-img'),
                            email: email,
                            cellphone: phone
                        },
                        success: function(res) {
                            if(res.code == 1) {
                                iosOverlay({
                                    text: res.reason,
                                    duration: 1500
                                });
                                $(".cover").hide();
                     		    $("#notice_pop").hide();
                            }
                        },
                        error: function() {
                            // console.log('购物车显示接口返回失败');
                        }
                    })
                }
            })
        },
        listChoose: function() {
            //属性选择
    		$(".product-concerns").on('click', '.consignee-item', function(){
                var $this = $(this);
                var curId = $this.attr('data-id');
                if($this.hasClass("item-selected")){
                    return false;
                }else{
                    $this.addClass("item-selected").siblings().removeClass("item-selected");
                }
                var chooseDom = $('.consignee-item.item-selected');
                var arr = [];
                $.each(chooseDom, function(index, item) {
                    arr.push($(item).attr('data-id'));
                })
                var arrlen = arr.length;
                var lastId = arr[arrlen-1];
                var str = arr.join(',');

                $.ajax({
                    url: wsCommon.host + '/api/goods/specDetail/' + wsCommon.getUrlParam('goodsId'),
                    dataType: wsCommon.jsonType,
                    data: {
                        specValueIds: str
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            var productsSpecListArr = res.data.productsSpecList;
                            var productsSpecList;
                            $.each(productsSpecListArr, function(index, item) {
                                if(item.specValueId == curId) {
                                    productsSpecList = item;
                                }
                            })
                            // var productsSpecList = res.data.productsSpecList[0];
                            $('[data-product="price"]').html('¥' + productsSpecList.price);
                            $('[data-product="bn"]').html(productsSpecList.bn);

                            if(productsSpecList.imageList) {
                                tempLength = 0;
                                var imageListTpl = '';
                                $.each(productsSpecList.imageList, function(index, item) {
                                    if(index == 0) {
                                        imageListTpl += '<li><img alt="'+item.imageName+'" bimg="'+item.lurl+'" src="'+item.murl+'" onmousemove="preview(this);" style="background-color: rgb(94, 177, 7);"></li>';
                                        $('[data-product="murl"] img').attr('src', item.murl).attr('jqimg', item.lurl);
                                    } else {
                                        imageListTpl += '<li><img alt="'+item.imageName+'" bimg="'+item.lurl+'" src="'+item.murl+'" onmousemove="preview(this);"></li>';
                                    }
                                })
                                $('[data-imageList="list"] ul').html(imageListTpl);
                            } else {
                                var imageListTpl = '';
                                $.each(chooseList, function(index, item) {
                                    if(index == 0) {
                                        imageListTpl += '<li><img alt="'+item.imageName+'" bimg="'+item.lurl+'" src="'+item.murl+'" onmousemove="preview(this);" style="background-color: rgb(94, 177, 7);"></li>';
                                        $('[data-product="murl"] img').attr('src', item.murl).attr('jqimg', item.lurl);
                                    } else {
                                        imageListTpl += '<li><img alt="'+item.imageName+'" bimg="'+item.lurl+'" src="'+item.murl+'" onmousemove="preview(this);"></li>';
                                    }
                                })
                                $('[data-imageList="list"] ul').html(imageListTpl);
                                $('[data-product="murl"] img').attr('src', chooseDefaul.murl).attr('jqimg', chooseDefaul.lurl);
                            }


                            // 判断库存
                            if(productsSpecList.store > 0) {
                                $('[data-product="store"]').html('<input type="button" style="cursor:pointer; border:0; width:142px; height:42px; background: url(images/btn-joincart.jpg) no-repeat 0 0" class="btn-major btn-huge action-addtocart btn-joincart" id="add_c" value="" data-role="addShopCart" data-style="info" data-price="'+productsSpecList.price+'" data-goodsid="'+productsSpecList.goodsId+'" data-productid="'+productsSpecList.productId+'" data-objtype="'+objTypes+'">');
                                $('.product-buy-quantity').show();
                                $('.product-buy-quantity .btn-decrease').attr('data-total', productsSpecList.store);
                                $('.product-buy-quantity .action-quantity-input').attr('data-total', productsSpecList.store);
                                $('.product-buy-quantity .btn-increase').attr('data-total', productsSpecList.store);

                                if(productsSpecList.fav) {
                                    $('[data-product="store"]').append('<a href="javascript:;" class="btn btn-faved" style="margin-left: 10px;"><em>已收藏</em></a>');
                                } else {
                                    $('[data-product="store"]').append('<a href="javascript:;" class="btn btn-addfav" data-role="addInfofav" style="margin-left: 10px;" data-goodsid="'+productsSpecList.goodsId+'" data-productid="'+productsSpecList.productId+'" data-name="'+productsSpecList.name+'" data-price="'+productsSpecList.price+'" data-img="'+imageIds+'"> <i class="icon"> F </i>收藏</a>');
                                }
                            } else {
                                $('[data-product="store"]').html('<button type="button" class="btn btn-caution btn-huge action-notify" id="notice" data-goodsid="'+productsSpecList.goodsId+'" data-productid="'+productsSpecList.productId+'" data-name="'+productsSpecList.name+'" data-price="'+productsSpecList.price+'" data-img="'+imageIds+'"><span><span>到货通知</span></span></button>');
                                $('.product-buy-quantity').hide();

                                if(productsSpecList.fav) {
                                    $('[data-product="store"]').append('<a href="javascript:;" class="btn btn-faved" style="margin-left: 10px;"><em>已收藏</em></a>');
                                } else {
                                    $('[data-product="store"]').append('<a href="javascript:;" class="btn btn-addfav" data-role="addInfofav" style="margin-left: 10px;" data-goodsid="'+productsSpecList.goodsId+'" data-productid="'+productsSpecList.productId+'" data-name="'+productsSpecList.name+'" data-price="'+productsSpecList.price+'" data-img="'+imageIds+'"> <i class="icon"> F </i>收藏</a>');
                                }
                            }
                        }
                    },
                    error: function() {

                    }
                })
    		})
        },
        ask: function() {
            $.ajax({
                url: wsCommon.host + '/api/member/queryUser',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    if(res.code == 1) {
                        if(res.result) {
                            $('[data-role="input-dis"] input').removeProp('disabled');
                            $('[data-role="asksubmit"]').removeProp('disabled');
                            $('[data-role="askarea"]').removeProp('disabled');
                            $('.mini-mask').hide();
                            $('.consult-title em').hide();

                            $('[data-role="askarea"]').charcount({
    						    position: 'none'
    						}).bind('update', function(evt, length, remaining) {
    						    $('.word-count .current').text(length);
    						});
                        }
                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function(e) {
                }
            })

            // 提交评论
            $('[data-role="asksubmit"]').on('click', function() {
                if($(this).prop('disabled')) return;

                var text = $('[data-role="askarea"]').val().trim();
                var hiddenName = $('[data-role="hiddenname"]').prop('checked') ? 'YES' : 'NO';
                if(text == '') {
                    iosOverlay({
                        text:'请填写咨询内容！',
                        duration: 1000
                    });
                    return;
                }
                $.ajax({
                    url: wsCommon.host + '/api/memberComments/saveAsk',
                    dataType: wsCommon.jsonType,
                    data: {
                        comment: text,
                        hiddenName: hiddenName,
                        gaskType: $('[data-role="input-dis"] input:checked').val(),
                        goodsId: $('[data-role="addShopCart"]').attr('data-goodsid'),
                        productId: $('[data-role="addShopCart"]').attr('data-productid')
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(!res.result) {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                                return;
                            }
                            iosOverlay({
                                text: '提交成功',
                                duration: 1000,
                                onbeforeshow: function() {
                                    $('[data-role="askarea"]').val('');
                                    $('.word-count .current').text(0)
                                }
                            });
                        } else {
                            iosOverlay({
                                text: res.reason,
                                duration: 1000
                            });
                        }
                    },
                    error: function(e) {
                    }
                })
            })
        },
        weekRank: function() {
            $.ajax({
                url: wsCommon.host + '/api/goods/listBuyWCountRank',
                dataType: wsCommon.jsonType,
                data: {
                    catId: wsCommon.getUrlParam('catId')
                },
                success: function(res) {
                    var list = res.data.pager.list;
                    var tpl = '';
                    $.each(list, function(index, item) {
                        tpl += '<li class="item clearfix  selected">\
                                 <div class="im"><a target="_blank" href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'"><img src="'+(item.defaultImage && item.defaultImage.surl)+'" alt="'+item.name+'" width="60" height="60"></a><span class="hl">'+(index+1)+'</span></div>\
                                 <div class="rank-box clearfix">\
                                     <div class="gname"><h6><a title="" target="_blank" href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'">'+item.name+'</a></h6></div>\
                                     <ul class="p"><li><span class="price1">¥'+item.price+'</span></li></ul>\
                                 </div>\
                            </li>';
                    })
                    $('[data-role="ranklist"]').html(tpl);
                },
                error: function() {
                    // console.log('error');
                }
            })
        },
        shortAsk: function() {
            $.ajax({
                url: wsCommon.host + '/api/memberComments/listGoodsAsk',
                dataType: wsCommon.jsonType,
                data: {
                    goodsId: $.getUrlParam('goodsId'),
                    pageSize: 2,
                    type: 0
                },
                success: function(res) {
                    if(res.code == 1) {
                        if(!res.result) {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
                            return;
                        }
                        $('[data-role="allask"]').html(res.data.count.countAll);
                        $('[data-role="goodsask"]').html(res.data.count.countGoods);
                        $('[data-role="afterask"]').html(res.data.count.countAfterSales);
                        var list = res.data.pager.list;
                        var tpl = '';
                        $.each(list, function(index, item) {
                            tpl += '<li class="consult-item">\
                                        <span class="icon icon-question">V</span>\
                                        <p class="question-content clearfix">\
                                          <span class="desc"><b>问：</b>'+item.commentContent+'</span>\
                                          <span class="name">'+item.author+' ('+item.memberLvName+')</span><span class="time">'+item.commentTimeStr+'</span>\
                                        </p>\
                                    </li>';
                        })
                        $('#consult_content_init').find('.switchable-panel').eq(0).find('.consult-list').html(tpl);
                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function(e) {
                }
            })

            $.ajax({
                url: wsCommon.host + '/api/memberComments/listGoodsAsk',
                dataType: wsCommon.jsonType,
                data: {
                    goodsId: $.getUrlParam('goodsId'),
                    pageSize: 2,
                    type: 1
                },
                success: function(res) {
                    if(res.code == 1) {
                        if(!res.result) {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
                            return;
                        }
                        var list = res.data.pager.list;
                        var tpl = '';
                        $.each(list, function(index, item) {
                            tpl += '<li class="consult-item">\
                                        <span class="icon icon-question">V</span>\
                                        <p class="question-content clearfix">\
                                          <span class="desc"><b>问：</b>'+item.commentContent+'</span>\
                                          <span class="name">'+item.author+' ('+item.memberLvName+')</span><span class="time">'+item.commentTimeStr+'</span>\
                                        </p>\
                                    </li>';
                        })
                        $('#consult_content_init').find('.switchable-panel').eq(1).find('.consult-list').html(tpl);
                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function(e) {
                }
            })

            $.ajax({
                url: wsCommon.host + '/api/memberComments/listGoodsAsk',
                dataType: wsCommon.jsonType,
                data: {
                    goodsId: $.getUrlParam('goodsId'),
                    pageSize: 2,
                    type: 2
                },
                success: function(res) {
                    if(res.code == 1) {
                        if(!res.result) {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
                            return;
                        }
                        var list = res.data.pager.list;
                        var tpl = '';
                        $.each(list, function(index, item) {
                            tpl += '<li class="consult-item">\
                                        <span class="icon icon-question">V</span>\
                                        <p class="question-content clearfix">\
                                          <span class="desc"><b>问：</b>'+item.commentContent+'</span>\
                                          <span class="name">'+item.author+' ('+item.memberLvName+')</span><span class="time">'+item.commentTimeStr+'</span>\
                                        </p>\
                                    </li>';
                        })
                        $('#consult_content_init').find('.switchable-panel').eq(2).find('.consult-list').html(tpl);
                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function(e) {
                }
            })
        },
        init: function() {
            this.listChoose();
            this.getDetailGoods();
            this.addFav();
            this.arrivalNotice();
            this.ask();
            this.weekRank();
            this.shortAsk();
        }
    }
    wsInfo.init();
})

var pageSize = 10;
var curPageAll = 1;
var curPageGoods = 1;
var curPageAfter = 1;
var allAsk = {
    getList: function() {
        $.ajax({
            url: wsCommon.host + '/api/memberComments/listGoodsAsk',
            dataType: wsCommon.jsonType,
            data: {
                goodsId: $.getUrlParam('goodsId'),
                pageSize: pageSize,
                type: 0
            },
            success: function(res) {
                if(res.code == 1) {
                    if(res.result) {
                        var pager = res.data.pager;

                        allAsk.initPaging(pager.pages, pager.total, res);
                    } else {
                        wsCommon.setCookie('go_back_link', window.location.href);
                        window.location.href = './passport-login.html';
                    }
                }
            },
            error: function() {
                // console.log('接口返回失败');
            }
        })
    },
    randerList: function(pageData) {
        var tpl = '';
        $.each(pageData, function(index, item) {
            tpl += '<li class="consult-item">\
                        <span class="icon icon-question">V</span>\
                        <p class="question-content clearfix">\
                          <span class="desc"><b>问：</b>'+item.commentContent+'</span>\
                          <span class="name">'+item.author+' ('+item.memberLvName+')</span><span class="time">'+item.commentTimeStr+'</span>\
                        </p>\
                    </li>';
        })
        $('#consult_content').find('.switchable-panel').eq(0).find('.consult-list').html(tpl);
    },
    getPageDates: function() {
        var self = this;

        $.ajax({
            url: wsCommon.host + '/api/memberComments/listGoodsAsk',
            dataType: wsCommon.jsonType,
            data: {
                goodsId: $.getUrlParam('goodsId'),
                pageSize: pageSize,
                type: 0,
                pageNum: curPageAll
            },
            success: function(res) {

                // 同步页码
                var totalPage = res.data.pager.pages;

                var pageData = res.data.pager.list;
                var pager = res.data.pager;
                self.randerList(pageData);
            },
            error: function() {
                // console.log('分页接口失败');
            }
        });
    },
    initPaging: function(totalPage, totalDataNum, res) {
        var self = this,
            ele = $('[data-role="dirPaging"]');
            if(totalDataNum > 0) {
                ele.show();
                var pagination = ele.pagination(totalDataNum, {
                    num_edge_entries: 1,
                    num_display_entries: 4,
                    callback: function(page_index) {
                        if(page_index == 0) {
                            var totalPage = res.data.pager.pages;

                            var pageData = res.data.pager.list;
                            var pager = res.data.pager;
                            allAsk.randerList(pageData);
                        } else {
                            curPageAll = page_index + 1;
                            allAsk.getPageDates();
                        }
                    },
                    items_per_page: pageSize,
                    prev_text: "&lt;&lt;上一页",
                    next_text: "下一页&gt;&gt;",
                    link_to: "javascript:;"
                });

            }else {
                ele.hide();
                allAsk.randerList([]);
            }
    }
}
allAsk.getList();

var goodsAsk = {
    getList: function() {
        $.ajax({
            url: wsCommon.host + '/api/memberComments/listGoodsAsk',
            dataType: wsCommon.jsonType,
            data: {
                goodsId: $.getUrlParam('goodsId'),
                pageSize: pageSize,
                type: 1
            },
            success: function(res) {
                if(res.code == 1) {
                    if(res.result) {
                        var pager = res.data.pager;

                        goodsAsk.initPaging(pager.pages, pager.total, res);
                    } else {
                        wsCommon.setCookie('go_back_link', window.location.href);
                        window.location.href = './passport-login.html';
                    }
                }
            },
            error: function() {
                // console.log('接口返回失败');
            }
        })
    },
    randerList: function(pageData) {
        var tpl = '';
        $.each(pageData, function(index, item) {
            tpl += '<li class="consult-item">\
                        <span class="icon icon-question">V</span>\
                        <p class="question-content clearfix">\
                          <span class="desc"><b>问：</b>'+item.commentContent+'</span>\
                          <span class="name">'+item.author+' ('+item.memberLvName+')</span><span class="time">'+item.commentTimeStr+'</span>\
                        </p>\
                    </li>';
        })
        $('#consult_content').find('.switchable-panel').eq(1).find('.consult-list').html(tpl);
    },
    getPageDates: function() {
        var self = this;

        $.ajax({
            url: wsCommon.host + '/api/memberComments/listGoodsAsk',
            dataType: wsCommon.jsonType,
            data: {
                goodsId: $.getUrlParam('goodsId'),
                pageSize: pageSize,
                type: 1,
                pageNum: curPageGoods
            },
            success: function(res) {

                // 同步页码
                var totalPage = res.data.pager.pages;

                var pageData = res.data.pager.list;
                var pager = res.data.pager;
                self.randerList(pageData);
            },
            error: function() {
                // console.log('分页接口失败');
            }
        });
    },
    initPaging: function(totalPage, totalDataNum, res) {
        var self = this,
            ele = $('[data-role="dirPaging1"]');
            if(totalDataNum > 0) {
                ele.show();
                var pagination = ele.pagination(totalDataNum, {
                    num_edge_entries: 1,
                    num_display_entries: 4,
                    callback: function(page_index) {
                        if(page_index == 0) {
                            var totalPage = res.data.pager.pages;

                            var pageData = res.data.pager.list;
                            var pager = res.data.pager;
                            goodsAsk.randerList(pageData);
                        } else {
                            curPageGoods = page_index + 1;
                            goodsAsk.getPageDates();
                        }
                    },
                    items_per_page: pageSize,
                    prev_text: "&lt;&lt;上一页",
                    next_text: "下一页&gt;&gt;",
                    link_to: "javascript:;"
                });

            }else {
                ele.hide();
                goodsAsk.randerList([]);
            }
    }
}
goodsAsk.getList();

var afterAsk = {
    getList: function() {
        $.ajax({
            url: wsCommon.host + '/api/memberComments/listGoodsAsk',
            dataType: wsCommon.jsonType,
            data: {
                goodsId: $.getUrlParam('goodsId'),
                pageSize: pageSize,
                type: 2
            },
            success: function(res) {
                if(res.code == 1) {
                    if(res.result) {
                        var pager = res.data.pager;

                        afterAsk.initPaging(pager.pages, pager.total, res);
                    } else {
                        wsCommon.setCookie('go_back_link', window.location.href);
                        window.location.href = './passport-login.html';
                    }
                }
            },
            error: function() {
                // console.log('接口返回失败');
            }
        })
    },
    randerList: function(pageData) {
        var tpl = '';
        $.each(pageData, function(index, item) {
            tpl += '<li class="consult-item">\
                        <span class="icon icon-question">V</span>\
                        <p class="question-content clearfix">\
                          <span class="desc"><b>问：</b>'+item.commentContent+'</span>\
                          <span class="name">'+item.author+' ('+item.memberLvName+')</span><span class="time">'+item.commentTimeStr+'</span>\
                        </p>\
                    </li>';
        })
        $('#consult_content').find('.switchable-panel').eq(2).find('.consult-list').html(tpl);
    },
    getPageDates: function() {
        var self = this;

        $.ajax({
            url: wsCommon.host + '/api/memberComments/listGoodsAsk',
            dataType: wsCommon.jsonType,
            data: {
                goodsId: $.getUrlParam('goodsId'),
                pageSize: pageSize,
                type: 2,
                pageNum: curPageGoods
            },
            success: function(res) {

                // 同步页码
                var totalPage = res.data.pager.pages;

                var pageData = res.data.pager.list;
                var pager = res.data.pager;
                self.randerList(pageData);
            },
            error: function() {
                // console.log('分页接口失败');
            }
        });
    },
    initPaging: function(totalPage, totalDataNum, res) {
        var self = this,
            ele = $('[data-role="dirPaging2"]');
            if(totalDataNum > 0) {
                ele.show();
                var pagination = ele.pagination(totalDataNum, {
                    num_edge_entries: 1,
                    num_display_entries: 4,
                    callback: function(page_index) {
                        if(page_index == 0) {
                            var totalPage = res.data.pager.pages;

                            var pageData = res.data.pager.list;
                            var pager = res.data.pager;
                            afterAsk.randerList(pageData);
                        } else {
                            curPageGoods = page_index + 1;
                            afterAsk.getPageDates();
                        }
                    },
                    items_per_page: pageSize,
                    prev_text: "&lt;&lt;上一页",
                    next_text: "下一页&gt;&gt;",
                    link_to: "javascript:;"
                });

            }else {
                ele.hide();
                afterAsk.randerList([]);
            }
    }
}
afterAsk.getList();
